#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <errno.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netinet/tcp.h>
#include "test_utils.h"

static int set_tcp_no_delay(int fd)
{
    int flag = 1;
    return setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, &flag, sizeof(flag));		
}

static int set_reuse_addr(int fd)
{
    int reuse = 1;
    return setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &reuse, sizeof(reuse));		
}

int main()
{
    int listen_fd = socket(AF_INET, SOCK_STREAM, 0);
    errno_assert(listen_fd != -1);

    int rc = set_reuse_addr(listen_fd);
    errno_assert(rc == 0);

    sockaddr_in addr  = {};
    addr.sin_family = AF_INET;
    addr.sin_port = htons(2650);

    rc = bind(listen_fd, (sockaddr*)&addr, sizeof(addr));
    errno_assert(rc == 0);

    rc = listen(listen_fd, 1);
    errno_assert(rc == 0);

    int child_fd = accept(listen_fd, 0, 0);
    errno_assert(child_fd != -1);

    printf("new connection accepted, start recv...\n");

    rc = set_tcp_no_delay(child_fd);
    errno_assert(rc == 0);

    char buf[2*1024*1024];

    while (true)
    {
        int len = recv(child_fd, buf, sizeof(buf), 0);    
        if (len <= 0)
            break;

        rc = send(child_fd, buf, len, 0);
        errno_assert(rc == len);
    }

    printf("recv completed, close connection now.\n");

    rc = close(child_fd);
    errno_assert(rc == 0);

    rc = close(listen_fd);
    errno_assert(rc == 0);

	return 0;
}

